package com.vanhung.speedtest;

import java.text.DecimalFormat;

import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

public abstract class AsyncNetWorker extends AsyncTask<String, Double, Double> implements SpeedChecker {

	//protected static final String TAG = AsyncDownloader.class.getSimpleName();

	protected final SpeedTestLauncher mainAct;

	protected final Button btnStart;

	protected final ProgressBar mProgressBar;

	protected final TextView mTxtProgress;

	protected final TextView mTxtDownSpeed;

	protected final TextView mTxtUploadSpeed;

	protected final ImageButton btnCancel;

	protected final DecimalFormat mDecimalFormater;

	public AsyncNetWorker(SpeedTestLauncher activity) {
		this.mainAct = activity;

		btnStart = (Button)mainAct.findViewById(R.id.btnStart);
		mProgressBar = (ProgressBar)mainAct.findViewById(R.id.progressBar);
		mTxtProgress = (TextView)mainAct.findViewById(R.id.progrNum);
		mTxtDownSpeed = (TextView)mainAct.findViewById(R.id.downSpeed);
		mTxtUploadSpeed = (TextView)mainAct.findViewById(R.id.uploadspeed);
		btnCancel = (ImageButton)mainAct.findViewById(R.id.btnCancel);

		mDecimalFormater = new DecimalFormat("##.#");
	}

	@Override
	protected Double doInBackground(String... urls) {
		return 1.0;
	}

	@Override
	protected void onProgressUpdate(Double... progress) {
		double percent = progress[0];
		double speed = progress[1];

		updateProgress(percent, speed);
	}

	@Override
	protected void onCancelled() {
		updateProgress(0, 0);
		mTxtProgress.setText("");
		mTxtDownSpeed.setText("");
		btnStart.setText(R.string.mainbtn_start);
		btnStart.setEnabled(true);
		btnCancel.setVisibility(View.INVISIBLE);
		mainAct.onCancel();
	}

	abstract protected void updateProgress(double percent, double speed);

	protected double calculate(final long time, final long bytesIn) {
		// from byte/millisecond to byte/second
		long bytespersecond = (bytesIn / time) * 1000;
		double kilobits = (float)(bytespersecond * BYTE_TO_KILOBIT);
		//double megabits = kilobits * KILOBIT_TO_MEGABIT;

		return kilobits;
	}
}
